#include "DatabaseSearchDialog.h"

DatabaseSearchDialog::DatabaseSearchDialog( DataBase *db, int SearchField, QWidget *parent ) : QDialog( parent )
{
    //Print( "DatabaseSearchDialog() is executed" );

    setWindowTitle( tr("Find Item") );

    if ( SearchField == -1 )
        this->SearchField = db->GetKeyField(); else
            this->SearchField = SearchField;

    Table = new StockTableView( db, this );

    SearchLabel = new QLabel( db->GetColumnHeader( this->SearchField ) );
    SearchEdit = new QLineEdit();
    SearchEdit->setFocus();

    SelectButton = new QPushButton( tr( "Select" ) );
    SelectButton->setDefault( true );
    CancelButton = new QPushButton( tr( "Cancel" ) );

    //Managing layouts
    SearchEditArea = new QHBoxLayout();
    SearchEditArea->addWidget( SearchLabel );
    SearchEditArea->addWidget( SearchEdit );

    Buttons = new QHBoxLayout();
    Buttons->addWidget( SelectButton );
    Buttons->addWidget( CancelButton );

    EditAndButtons = new QHBoxLayout();
    EditAndButtons->addLayout( SearchEditArea );
    EditAndButtons->addSpacing( 50 );
    EditAndButtons->addLayout( Buttons );

    MainLayout = new QVBoxLayout();
    MainLayout->addWidget( Table );
    MainLayout->addLayout( EditAndButtons );

    this->setLayout( MainLayout );

    SearchEdit->setFocus();

    //Slots and signals
    connect( SearchEdit, SIGNAL( textChanged( const QString& ) ),
             Table, SLOT(FindItem( const QString& )) );

    connect( CancelButton, SIGNAL(clicked()), this, SLOT(close()) );
    connect( SelectButton, SIGNAL(clicked()), Table, SLOT(GetSelectedItem()) );

    connect( Table, SIGNAL(NoItemIsSelected()), this, SLOT(NoItemIsSelected()) );
    connect( Table, SIGNAL(Item(ItemType)), this, SIGNAL(Item(ItemType)) );
    connect( Table, SIGNAL(Item(ItemType)), this, SLOT(close()) );

}

DatabaseSearchDialog::~DatabaseSearchDialog()
{
    delete Table;

    delete SearchLabel;
    delete SearchEdit;

    delete SelectButton;
    delete CancelButton;

    delete SearchEditArea;
    delete Buttons;
    delete EditAndButtons;
    delete MainLayout;
}

void DatabaseSearchDialog::NoItemIsSelected()
{
    QMessageBox MB(QMessageBox::Information, "Information", "No item is selected", QMessageBox::Ok, this);
    MB.exec();
}

void DatabaseSearchDialog::closeEvent ( QCloseEvent * event )
{
    clear();
}

void DatabaseSearchDialog::clear()
{
    SearchEdit->clear();
    SearchEdit->setFocus();
}
